﻿using System;
using System.IO;
using System.Reflection;
using System.Globalization;
using System.Resources;
using System.Collections.Generic;

namespace SBPweb.MediaCenter.Common.Resources
{
    public class ResourceHandler
    {

        #region Protected fields

        protected Dictionary<CultureInfo, ResourceSet> pResourceSets = new Dictionary<CultureInfo, ResourceSet>();

        #endregion

        #region Constructor logic

        public ResourceHandler(Type type, List<CultureInfo> cultures)
        {

            foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures | CultureTypes.NeutralCultures))
            {
                if (cultures.Contains(ci))
                {
                    try
                    {
                        Assembly satellite = type.Assembly.GetSatelliteAssembly(ci);
                        Stream s = satellite.GetManifestResourceStream(satellite.GetManifestResourceNames()[0]);
                        ResourceSet rs = new ResourceSet(s);
                        pResourceSets.Add(ci, rs);
                    }
                    catch (FileNotFoundException)
                    {
                    }
                }
            }
        }

        #endregion

        #region Public methods

        public string GetString(string name)
        {
            return GetString(name, CultureInfo.CurrentUICulture);
        }

        public string GetString(string name, CultureInfo culture)
        {
            return pResourceSets[culture].GetString(name);
        }

        public object GetObject(string name)
        {
            return GetString(name, CultureInfo.CurrentUICulture);
        }

        public object GetObject(string name, CultureInfo culture)
        {
            return pResourceSets[culture].GetObject(name);
        }

        #endregion

        #region Public static helper functions

        public static object GetAssemblyCustomAttribute<T>(Assembly asm) where T : Attribute
        {
            foreach (CustomAttributeData cad in CustomAttributeData.GetCustomAttributes(asm))
            {
                if (cad.Constructor.DeclaringType == typeof(T))
                {
                    return cad.ConstructorArguments[0].Value;
                }
            }
            return null;
        }

        #endregion

    }
}
